<?php

namespace App\Jobs\Schedule;

use App\Models\Schedule\ScheduleUserChangeLogModel;
use App\Models\Schedule\ScheduleUserModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ScheduleUserChangeLogJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private int   $ruleId;
    private int   $shopId;
    private array $beforeRule;
    private array $affectIds;

    /**
     * 生成未来的排班变更记录
     *
     * @return void
     */
    public function __construct(int $ruleId, int $shopId, array $beforeRule, array $affectIds)
    {
        $this->ruleId     = $ruleId;
        $this->shopId     = $shopId;
        $this->beforeRule = $beforeRule;
        $this->affectIds  = $affectIds;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        ScheduleUserModel::query()
                         ->withoutGlobalScope('isDel')
                         ->whereIn('id', $this->affectIds)
                         ->get()
                         ->each(function (ScheduleUserModel $scheduleUserModel) {

                             $beforeData = $scheduleUserModel->toArray();
                             $beforeData['ruleName']  = $this->beforeRule['name'];
                             $beforeData['ruleStart'] = $this->beforeRule['start'];
                             $beforeData['ruleEnd']   = $this->beforeRule['end'];
                             $beforeData['color']     = $this->beforeRule['color'];

                             if ($scheduleUserModel->isDeleted == 1) {
                                 $afterData = [];
                             } else {
                                 $afterData = $scheduleUserModel->toArray();
                             }

                             // 变更日志
                             (new ScheduleUserChangeLogModel())
                                 ->setBeforeData($beforeData)
                                 ->setAfterData($afterData)
                                 ->add($this->shopId, $scheduleUserModel->userId, $scheduleUserModel->date,
                                     $this->ruleId, ScheduleUserChangeLogModel::TYPE_RULE);
                         });
    }

    /**
     * 受影响的schedule_user_ids
     * @param int $shopId
     * @param int $ruleId
     * @return array
     */
    public static function getAffectIds(int $shopId, int $ruleId)
    {
        return ScheduleUserModel::query()
                                      ->where('shopId', $shopId)
                                      ->where('ruleId', $ruleId)
                                      ->where('date', '>=', date('Ymd'))
                                      ->pluck('id')
                                      ->toArray();
    }
}
